import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';
import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/we3_method.dart';
import 'package:aichat_flutter_wallet/module/module_browser/widget/browser_fail.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/provider/nav_key.dart';
import '../../module_trade/pages/trade_transfer.dart';

class BrowserWebViewWidget extends StatefulWidget {
  String url;

  BrowserWebViewWidget({super.key,required this.url, this.userScripts});

  List<String>? userScripts;

  @override
  State<BrowserWebViewWidget> createState() => _BrowserWebViewWidgetState();
}

class _BrowserWebViewWidgetState extends State<BrowserWebViewWidget> {
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
          useShouldOverrideUrlLoading: true,
          mediaPlaybackRequiresUserGesture: false,
          transparentBackground: true),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  // 下拉控制
  late PullToRefreshController pullToRefreshController;
  bool isShowDialog = false;
  bool isLoadSuccess = true;
  bool isFailed = false;

  void doShowDialog() {
    DialogUtils.showBrowserLoading(context);
  }

  void colseDialog() {
    if (isShowDialog) {
      setState(() {
        isShowDialog = false;
      });
      // BrowserProvider.close();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
          // color: '#8667FE'.toColor(),
          color: AppColors.c_8667FE),
      onRefresh: () async {
        // doShowDialog();
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    webViewController = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<BrowserProvider>(builder: (c, browser, child) {
      bool isFirstLoad = false;
      return Container(
        height: double.infinity,
        width: double.infinity,
        child: IndexedStack(
          index: isFailed == false ? 0 : 1,
          children: [
            Column(
              children: [
                Visibility(
                    visible: browser.progress < 1,
                    child: SizedBox(
                      height: 2.w,
                      child: LinearProgressIndicator(
                        backgroundColor: Colors.transparent,
                        color: Color.fromRGBO(134, 103, 254, 1),
                        value: browser.progress,
                      ),
                    )),
                Visibility(
                    visible: browser.progress >= 1,
                    child: Container(
                      height: 2.w,
                    )),
                Expanded(
                    child: SizedBox(
                        height: MediaQuery.of(context).size.height -
                            88 -
                            MediaQuery.of(context).padding.top,
                        child: InAppWebView(
                          key: webViewKey,
                          initialOptions: options,
                          initialUrlRequest:
                              URLRequest(url: Uri.parse(widget.url)),
                          pullToRefreshController: pullToRefreshController,
                          onWebViewCreated: (controller) async {
                            webViewController = controller;
                            browser.initController(controller, context);
                            browser.setNetworkAndNode();
                            controller.addJavaScriptHandler(
                                handlerName: 'postMessage',
                                callback: (args) {
                                  // 进行处理
                                  var resp = json.decode(args[0]);

                                  if (resp['route'] == 'TradeTransferPage') {
                                    Navigator.of(NavKey.getContext())
                                        .push(MaterialPageRoute(
                                            builder: (_) {
                                              return TradeTransferPage(
                                                  contract: resp['contract'],
                                                  toAddress: resp['toAddress']);
                                            },
                                            maintainState: false));

                                    // Navigator.of(context).pop();
                                  } else {
                                    Web3MethodCall(controller)
                                        .checkMethodCall(args[0]);
                                  }
                                });
                            // 单独监听 h5 唤起原生端
                            controller.addJavaScriptHandler(
                                handlerName: 'linkJoinGroup',
                                callback: (args) {
                                  NativeChannelBridge().h5CallNative(
                                      "linkJoinGroup", json.decode(args[0]));
                                });
                          },
                          onLoadStart: (controller, url) {
                            Log.logger.d(
                                'onLoadStart--------------------------${url}');
                          },
                          initialUserScripts: UnmodifiableListView<UserScript>(
                              widget.userScripts!.map((e) => UserScript(
                                  source: e,
                                  injectionTime: UserScriptInjectionTime
                                      .AT_DOCUMENT_START))),
                          onLoadStop: (controller, url) async {
                            try {
                              if (isFirstLoad) {
                                return;
                              }
                              isFirstLoad = true;
                              if (webViewController != null &&
                                  Platform.isAndroid) {
                                // 针对 项目中存在 iframe 里 有 web3的处理操作问题
                                await webViewController!
                                    .evaluateJavascript(source: '''
                                  (function() {
                                    var iframes= document.getElementsByTagName('iframe');
                                    if(!iframes.length){
                                      return;
                                    }
                                    for(var i = 0; i<iframes.length;i++){
                                       // 不管 每个iframe 都给它 注入 
                                       var iframe = iframes[i];
                                       console.log(iframe);
                                       iframe.contentWindow.ethereum = window.ethereum; 
                                       console.log(iframe.contentWindow.ethereum,"打印iframe");
                                    }
                                  })();
                                ''');
                              }
                              // 避免加载失败也会保存
                              if (!isFailed) {
                                browser.addCacheInfo(url.toString());
                              }
                              isFirstLoad = false;
                            } catch (e) {
                              isFirstLoad = false;
                              kaiPrint('error:${e}');
                            }
                          },
                          onLoadError: (controller, url, code, message) {
                            if (code < 0 && isFailed == false) {
                              setState(() {
                                isFailed = true;
                              });
                              return;
                            }
                          },
                          onLoadHttpError: (controller, url, code, message) {
                          },
                          onProgressChanged: (controller, progress) {
                            if (progress < 10 ||
                                (browser.progress >= 1 && progress >= 100)) {
                              return;
                            }
                            // Log.logger.e('progress ------${progress}');
                            browser.setProgress(progress / 100);
                          },
                          onConsoleMessage: (controller, consoleMessage) {
                            Log.logger.d(consoleMessage.message);
                          },
                          shouldOverrideUrlLoading:
                              (controller, navigationAction) async {
                            var uri = navigationAction.request.url!;
                            if (![
                              "http",
                              "https",
                              "file",
                              "chrome",
                              "data",
                              "javascript",
                              "about"
                            ].contains(uri.scheme)) {
                              return NavigationActionPolicy.CANCEL;
                            }
                            if (webViewController != null && Platform.isIOS) {
                              // 针对 项目中存在 iframe 里 有 web3的处理操作问题
                              await webViewController!
                                  .evaluateJavascript(source: '''
                                  (function() {
                                    var iframes= document.getElementsByTagName('iframe');
                                    if(!iframes.length){
                                      return;
                                    }
                                    for(var i = 0; i<iframes.length;i++){
                                       // 不管 每个iframe 都给它 注入 
                                       var iframe = iframes[i];
                                       console.log(iframe);
                                       iframe.contentWindow.ethereum = window.ethereum; 
                                       console.log(iframe.contentWindow.ethereum,"打印iframe");
                                    }
                                  })();
                                ''');
                            }
                            return NavigationActionPolicy.ALLOW;
                          },
                        )))
              ],
            ),
            BrowserFail(callBack: () {
              setState(() {
                isFailed = false;
              });
            }),
          ],
        ),
      );
    });
  }
}
